package com.yuanqi.controller;

import com.yuanqi.domain.Receipt;
import com.yuanqi.service.ReceiptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/finance/receipts")
@CrossOrigin(origins = "*")
public class ReceiptController {
    
    @Autowired
    private ReceiptService receiptService;
    
    @GetMapping
    public ResponseEntity<List<Receipt>> getAllReceipts() {
        List<Receipt> receipts = receiptService.getAllReceipts();
        return ResponseEntity.ok(receipts);
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<Receipt> getReceiptById(@PathVariable Long id) {
        Optional<Receipt> receipt = receiptService.getReceiptById(id);
        return receipt.map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    @GetMapping("/customer/{customerId}")
    public ResponseEntity<List<Receipt>> getReceiptsByCustomer(@PathVariable Long customerId) {
        List<Receipt> receipts = receiptService.getReceiptsByCustomer(customerId);
        return ResponseEntity.ok(receipts);
    }
    
    @GetMapping("/date-range")
    public ResponseEntity<List<Receipt>> getReceiptsByDateRange(
            @RequestParam LocalDate startDate,
            @RequestParam LocalDate endDate) {
        List<Receipt> receipts = receiptService.getReceiptsByDateRange(startDate, endDate);
        return ResponseEntity.ok(receipts);
    }
    
    @PostMapping
    public ResponseEntity<Receipt> createReceipt(@RequestBody Receipt receipt) {
        try {
            Receipt createdReceipt = receiptService.createReceipt(receipt);
            return ResponseEntity.ok(createdReceipt);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<Receipt> updateReceipt(@PathVariable Long id, @RequestBody Receipt receiptDetails) {
        try {
            Receipt updatedReceipt = receiptService.updateReceipt(id, receiptDetails);
            return ResponseEntity.ok(updatedReceipt);
        } catch (RuntimeException e) {
            return ResponseEntity.notFound().build();
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteReceipt(@PathVariable Long id) {
        receiptService.deleteReceipt(id);
        return ResponseEntity.ok().build();
    }
    
    @GetMapping("/stats/total-amount")
    public ResponseEntity<Double> getTotalReceiptAmount(
            @RequestParam LocalDate startDate,
            @RequestParam LocalDate endDate) {
        Double totalAmount = receiptService.getTotalReceiptAmount(startDate, endDate);
        return ResponseEntity.ok(totalAmount != null ? totalAmount : 0.0);
    }
}


